<template>
  <div class="main-container">
    <div class="mb10">
      <el-radio-group v-model="showState" size="mini" @change="showStateChange" v-if="$checkAuth('userManagement')">
        <el-radio-button label="0">查看全部</el-radio-button>
        <el-radio-button label="1">仅看在职</el-radio-button>
        <el-radio-button label="2">仅看离职</el-radio-button>
      </el-radio-group>
      <el-button class="ml20" type="primary" icon="el-icon-plus" @click="addUser()" v-if="$checkAuth('userManagement')">添加人员</el-button>
      <el-button type="primary" icon="el-icon-plus" @click="routeToRoleManager()" v-if="$checkAuth('roleManagement')">角色管理</el-button>
      <el-button type="primary" icon="el-icon-plus" @click="routeToAuthorityManager()" v-if="$checkAuth('authorityManagement')">权限管理</el-button>
    </div>
    <div class="h-100percent overflow-auto">
      <el-table border stripe :data="userList">
        <el-table-column label="序号" type="index" align="center" width="60"></el-table-column>
        <el-table-column prop="jobNumber" label="工号" align="center" width="100"></el-table-column>
        <el-table-column prop="userName" label="姓名" align="center" width="100"></el-table-column>
        <el-table-column prop="telephone" label="联系方式" align="center" width="160"></el-table-column>
        <el-table-column label="角色" align="center" width="150">
          <template slot-scope="scope">
            <div class="mb5" v-for="(role, index) in scope.row.roles" :key="index">
              <el-button size="mini" type="success" plain>{{ role.roleName }}</el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" width="100">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.state" active-color="#13ce66" inactive-color="#ff4949" @change="userStateChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" align="center" min-width="120"></el-table-column>
        <el-table-column prop="operation" align="center" fixed="right" width="450" label="操作">
          <template slot-scope="scope">
            <div v-if="scope.row.state == true">
              <el-button type="primary" size="mini" @click="modifyUser(scope.row)" v-if="$checkAuth('用户管理') && scope.row.jobNumber != 'BL000'">修改</el-button>
              <el-button type="primary" size="mini" @click="openAuthorityDialog(scope.row)" v-if="$checkAuth('用户管理') && scope.row.jobNumber != 'BL000'">权限设置</el-button>
              <el-button type="primary" size="mini" @click="initPassword(scope.row)" v-if="$checkAuth('用户管理') && scope.row.jobNumber != 'BL000'">重置密码</el-button>
              <el-button type="primary" size="mini" @click="openMessageDialog(scope.row)" v-if="$checkAuth('用户管理') && scope.row.jobNumber != 'BL000'">消息订阅</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 弹框：用户新建/修改 -->
    <el-dialog :title="userDialogTitle" :visible.sync="userDialogVisible" width="25%" :close-on-click-modal="false" @close="closeUserDialog()">
      <el-form label-width="100px" :model="currentUser" :rules="user_input_rules">
        <el-form-item label="工号" prop="jobNumber">
          <el-input class="inline-input w150" v-model="currentUser.jobNumber" placeholder="请输入工号"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="userName">
          <el-input class="inline-input w150" v-model="currentUser.userName" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="telephone">
          <el-input class="inline-input w150" v-model="currentUser.telephone" placeholder="请输入联系方式"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="roleIds">
          <el-select v-model="currentUser.roleIds" multiple placeholder="请选择角色">
            <el-option v-for="(role, index) in roleList" :key="index" :value="role.roleId" :label="role.roleName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input class="w200" type="textarea" :row="5" v-model="currentUser.remark"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="saveUser()">保存</el-button>
          <el-button @click="closeUserDialog()">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 弹框：消息订阅 -->
    <el-dialog title="消息订阅" :visible.sync="messageDialogVisible" width="65%" :close-on-click-modal="false" @close="closeMessageDialog()">
      <el-form>
        <el-form-item v-for="(item, index) in Object.keys(topicList)" :key="index">
          <div class="mb10 fontSize16 bold">{{ item }}</div>
          <span class="mr20" v-for="topic in topicList[item]" :key="topic.topicId">
            <el-checkbox v-model="topic.selected" :label="topic.topicName"></el-checkbox>
          </span>
        </el-form-item>
      </el-form>
      <br />
      <el-button type="primary" @click="saveSubscription()">保存</el-button>
      <el-button @click="closeMessageDialog()">取消</el-button>
    </el-dialog>

    <!-- 弹框：权限设置 -->
    <el-dialog title="权限设置" :visible.sync="authorityDialogVisible" width="65%" :close-on-click-modal="false" @close="closeAuthorityDialog()">
      <el-form>
        <el-form-item v-for="(item, index) in Object.keys(authorityCheckData)" :key="index">
          <div class="mb10 fontSize16 bold">{{ item }}</div>
          <span class="mr20" v-for="authority in authorityCheckData[item]" :key="authority.authorityId">
            <el-checkbox v-model="authority.selected" :label="authority.authorityName"></el-checkbox>
          </span>
        </el-form-item>
      </el-form>
      <br />
      <el-button type="primary" @click="saveAuthorityChange()">保存</el-button>
      <el-button type="primary" @click="initAuthorityDialogData()">重置</el-button>
      <el-button @click="closeAuthorityDialog()">取消</el-button>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import { Notification } from 'element-ui'
import _ from 'lodash'

// 消息模块接口
import { getMessageTopicList, setUserSubscription } from '@/api/message/message'
// 用户模块接口
import { changeStateApi, initPasswordApi, saveUserApi, getUserListApi } from '@/api/authority/api-authority'
// 角色模块接口
import { getRoleListApi } from '@/api/authority/api-authority'
// 权限模块接口
import { getAuthorityListApi, saveUserAuthorityApi } from '@/api/authority/api-authority'

@Component<UserManagement>({
  components: {}
})
export default class UserManagement extends Vue {
  //页面初始化
  created() {
    // 获取用户列表
    this.getUserList(true)
    // 获取角色列表
    this.getRoleList()
    // 获取权限列表
    this.getAuthorityList()
  }

  routeToAuthorityManager() {
    this.$router.push({ name: 'authority-manager' })
  }
  routeToRoleManager() {
    this.$router.push({ name: 'role-manager' })
  }
  /********************************************************************************************************************
   * 用户管理功能 代码开始 **********************************************************************************************
   ********************************************************************************************************************/
  // 查看不同状态的用户 单选框绑定值 0-全部 1-在职 2-离职
  showState: string = '1'
  showStateChange(stateLabel) {
    if (stateLabel == '0') this.getUserList('')
    else if (stateLabel == '1') this.getUserList(true)
    else if (stateLabel == '2') this.getUserList(false)
  }

  // 系统用户列表
  userList: any = []

  // 系统角色列表
  roleList: any = []

  // 用户新建/修改弹框 可见控制
  userDialogVisible: boolean = false

  // 用户新建/修改弹框 标题
  userDialogTitle: string = ''

  // 当前新建/修改的用户
  currentUser: any = {}

  // 获取用户列表
  async getUserList(onTheJob: any) {
    await getUserListApi({ onTheJob: onTheJob })
      .catch(err => Notification.error(err))
      .then((res: any) => (this.userList = res.data))
  }

  // 获取角色列表
  async getRoleList() {
    await getRoleListApi({ rich: false })
      .catch(err => Notification.error(err))
      .then((res: any) => (this.roleList = res.data))
  }

  // 新建用户
  addUser() {
    // 实际上打开新建用户的弹框
    this.userDialogTitle = '新增用户'
    this.currentUser = {
      userId: -1,
      userName: '',
      jobNumber: '',
      telephone: '',
      remark: '',
      roleIds: []
    }
    this.userDialogVisible = true
  }

  // 修改用户
  modifyUser(user) {
    // 实际上打开修改用户的弹框
    this.userDialogTitle = '修改用户'
    this.currentUser = {
      userId: user.userId,
      userName: user.userName,
      jobNumber: user.jobNumber,
      telephone: user.telephone,
      remark: user.remark,
      roleIds: user.roles.map(role => role.roleId)
    }
    this.userDialogVisible = true
  }

  // 保存用户
  saveUser() {
    this.saveUserReq().then(() => {
      this.getUserList(true)
      this.closeUserDialog()
    })
  }

  // 保存新建/修改：判断交给后端去做（根据ID）
  async saveUserReq() {
    await saveUserApi(this.currentUser).catch(err => Notification.error(err))
  }

  // 关闭用户新建/修改弹框
  closeUserDialog() {
    this.currentUser = {}
    this.userDialogTitle = ''
    this.userDialogVisible = false
  }

  // 用户在职状态变化
  userStateChange(user) {
    let userStr = user.jobNumber + '-' + user.userName
    let stateStr = user.state == true ? '在职' : '离职'
    this.$confirm('请确认调整用户：' + userStr + ' 的状态为：' + stateStr, '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消'
    })
      .then(() => {
        let params = {
          userId: user.userId,
          state: user.state
        }
        this.changeUserStateReq(params).then(() => {
          this.showState = '1'
          this.getUserList(true)
        })
      })
      .catch(() => (user.state = !user.state))
  }
  async changeUserStateReq(params) {
    await changeStateApi(params).catch(res => Notification.error(res))
  }

  initPassword(user) {
    this.$confirm('请确认重置用户: ' + user.jobNumber + '-' + user.userName + '密码', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消'
    }).then(() => this.initPasswordReq(user.userId))
  }
  // 重置密码
  async initPasswordReq(userId) {
    await initPasswordApi({ userId: userId }).catch(res => Notification.error(res))
  }

  // 新建/修改用户弹框 表单输入规则
  checkPhone = (rule, value, callback) => {
    if (!value || /^0\d{2,3}-?\d{7,8}$/.test(value) || /^1(3|4|5|6|7|8|9)\d{9}$/.test(value)) {
      callback()
    } else {
      callback(new Error('电话格式输入不正确'))
    }
  }
  checkJobNumber = (rule, value, callback) => {
    if (!value) {
      return callback(new Error('不能为空'))
    }
    if (/^BL\d{3}$/.test(value)) {
      callback()
    } else {
      callback(new Error('请输入正确格式的工号:BL + 三位数字'))
    }
  }
  user_input_rules = {
    jobNumber: [
      { required: true, message: '工号不能为空！', trigger: 'blur' },
      { validator: this.checkJobNumber, trigger: 'blur' }
    ],
    userName: [{ required: true, message: '姓名不能为空！', trigger: 'blur' }],
    telephone: [{ validator: this.checkPhone, trigger: 'blur' }]
  }

  /***********************
   * 用户管理功能 代码结束 *
   ********************* */
  /********************************************************************************************************************
   * 权限设置功能 代码开始 **********************************************************************************************
   ********************************************************************************************************************/

  // 弹框开闭控制
  authorityDialogVisible: boolean = false

  // 系统权限列表
  authorityList: any = []

  // 权限分组列表 by authorityObj
  authorityCheckData: any = {}

  // 当前设置权限的用户
  currentChangeAuUser: any

  // 获取权限列表
  async getAuthorityList() {
    await getAuthorityListApi({ rich: false })
      .catch(err => Notification.error(err))
      .then((res: any) => (this.authorityList = res.data))
  }

  // 关闭权限设置弹框 并 清空相关数据
  closeAuthorityDialog() {
    this.currentChangeAuUser = {}
    this.authorityCheckData = {}
    this.authorityDialogVisible = false
  }

  // 打开权限设置弹框 并 初始化相关数据
  openAuthorityDialog(user) {
    this.currentChangeAuUser = user
    this.authorityDialogVisible = true
    this.initAuthorityDialogData()
  }
  initAuthorityDialogData() {
    let tempAuList = this.authorityList.map(authority => {
      if (this.currentChangeAuUser.authorityIds.indexOf(authority.authorityId) != -1) {
        this.$set(authority, 'selected', true)
      } else {
        this.$set(authority, 'selected', false)
      }
      return authority
    })
    this.authorityCheckData = {}
    for (let i = 0; i < tempAuList.length; i++) {
      let authority = tempAuList[i]
      if (Object.keys(this.authorityCheckData).indexOf(authority.authorityObj) == -1) {
        this.authorityCheckData[authority.authorityObj] = []
      }
      this.authorityCheckData[authority.authorityObj].push(authority)
    }
  }

  // 保存权限设置
  saveAuthorityChange() {
    let selectedAuthorityIds: any = []
    // 遍历筛选被选中的主题
    for (let key of Object.keys(this.authorityCheckData)) {
      for (let authority of this.authorityCheckData[key]) {
        if (authority.selected) {
          selectedAuthorityIds.push(authority.authorityId)
        }
      }
    }
    let params = {
      userId: this.currentChangeAuUser.userId,
      authorityIds: selectedAuthorityIds
    }
    console.log('权限设置请求参数')
    console.log(params)

    this.saveUserAuthorityReq(params).then(() => {
      this.getUserList(true)
      this.closeAuthorityDialog()
    })
  }
  async saveUserAuthorityReq(params) {
    await saveUserAuthorityApi(params).catch(err => Notification.error(err))
  }
  /***********************
   * 权限设置功能 代码结束 *
   ********************* */
  /********************************************************************************************************************
   * 消息订阅功能 代码开始 **********************************************************************************************
   ********************************************************************************************************************/

  // 弹框开闭控制
  messageDialogVisible: boolean = false

  // 消息主题列表
  messageTopicList: any = []

  // 消息主题列表 按照topicObj分组
  topicList: any = {}

  // 当前订阅用户
  subscriber: any = {}

  // 已订阅（选中）主题列表
  topicSubscribeList: any = []

  // 关闭消息订阅弹框 同时清空数据
  closeMessageDialog() {
    this.subscriber = {}
    this.topicList = {}
    this.topicSubscribeList = []
    this.messageDialogVisible = false
  }
  // 打开消息订阅弹框 同时获取消息主题列表
  openMessageDialog(row) {
    this.subscriber = row
    // 获取消息主题列表
    this.getMessageTopicList().then(() => {
      // 初始化消息主题数据格式
      this.initTopicListForCheckBox()
      this.messageDialogVisible = true
    })
  }
  async getMessageTopicList() {
    await getMessageTopicList({})
      .catch(err => {
        Notification.error(err)
      })
      .then((res: any) => {
        this.messageTopicList = res.data
      })
  }
  initTopicListForCheckBox() {
    this.messageTopicList = this.messageTopicList.map(item => {
      if (this.subscriber.subscribedTopicIds.indexOf(item.topicId) != -1) {
        this.$set(item, 'selected', true)
      } else {
        this.$set(item, 'selected', false)
      }
      return item
    })
    for (let i = 0; i < this.messageTopicList.length; i++) {
      let topic = this.messageTopicList[i]
      if (Object.keys(this.topicList).indexOf(topic.topicObj) == -1) {
        this.topicList[topic.topicObj] = []
      }
      this.topicList[topic.topicObj].push(topic)
    }
  }

  // 保存订阅
  saveSubscription() {
    this.topicSubscribeList = []
    // 遍历筛选被选中的主题
    for (let key of Object.keys(this.topicList)) {
      for (let topic of this.topicList[key]) {
        if (topic.selected) {
          this.topicSubscribeList.push(topic.topicId)
        }
      }
    }
    let params = {}
    params['userId'] = this.subscriber.userId
    params['messageTopicIds'] = this.topicSubscribeList
    // 用户确认是否同步
    this.$confirm('是否同步新订阅主题最近的消息', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(() => {
        this.submitSubscription(params, true)
      })
      .catch(() => {
        this.submitSubscription(params, false)
      })
  }
  async submitSubscription(params, synchronizeHistory) {
    params['synchronizeHistory'] = synchronizeHistory
    await setUserSubscription(params)
      .catch(err => {
        Notification.error(err)
      })
      .then(() => {
        this.getUserList(true)
        this.closeMessageDialog()
      })
  }
  /***********************
   * 消息订阅功能 代码结束 *
   ********************* */
  /********************************************************************************************************************
   ********************************************************************************************************************
   ********************************************************************************************************************/
}
</script>
<style lang="scss" scoped>
.equipmentName {
  text-indent: 5px;
}
</style>
